package handlers

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"store/cache"
	"store/models"
	"store/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	login := "login"
	count, _ := cache.Rdb.Get(cache.Ctx, login).Int()
	if count >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "错误次数超过三次，禁止登录",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Init(password) {
		cache.Rdb.Incr(cache.Ctx, login)
		if count >= 2 {
			cache.Rdb.Set(cache.Ctx, login, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "错误次数过多，封禁两小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

}
